import { defineAsyncComponent } from "vue"
import Layout from "@/layout/layout.vue"

// src/utils/router.ts
export const viewModules = import.meta.glob('@/pages/**/*.vue')

export function loadComponent(componentPath) {
    const fullPath = `/src/pages/${componentPath}.vue`
    const component = viewModules[fullPath]
    if (!component) {
        // console.error(`组件路径不存在: ${fullPath}`)
    }
    return component
}


export function mapMenuToRoutes(menuList) {
    const routes = []

    menuList.forEach(menu => {

        const route = {
            path: menu.path,
            name: menu.id,
            component: menu.component === "Layout"
                ? Layout
                : loadComponent(menu.component),
            meta: menu.meta,

        }

        if (menu.children && menu.children.length > 0) {
            if (menu.component === "Layout") {
                route.children = menu.children.map(child => ({
                    path: child.path,
                    name: child.id,
                    component: loadComponent(child.component),
                    meta: child.meta || {}
                }))
            }
        }

        routes.push(route)
    })

    return routes
}

// 获取第一个动态路由路径
export function findFirstValidPath(menuList) {
    for (const menu of menuList) {
        if (menu.children && menu.children.length > 0) {
            return menu.children[0].url
        } else if (menu.url) {
            return menu.url
        }
    }
    return '/'
}
